package com.tecrun.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.tecrun.common.constant.IndexConstants;
import com.tecrun.common.core.redis.RedisCache;
import com.tecrun.common.utils.http.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.core.env.Environment;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ElasticSearchClientUtil {

    @Autowired
    Environment environment;

    @Autowired
    RedisCache redisCache;

    private static RestHighLevelClient client;

    private static final String LOCK = "archive:create:file_";


    public RestHighLevelClient getClient() {
        String host = environment.getProperty("elasticsearch.host");
        String port = environment.getProperty("elasticsearch.port");
        log.info(" ElasticSearchClient ## connection host:{}, port:{}", host, port);
        if (client == null) {
            assert host != null;
            assert port != null;
            client = new RestHighLevelClient(
                    RestClient.builder(new HttpHost(host, Integer.parseInt(port), "http")));
        }
        log.info(" ElasticSearchClient ## connection success ... ");
        return client;
    }

    /**
     * @throws IOException
     */
    public static void closeClient() throws IOException {
        if (client != null) {
            client.close();
        }
    }

    /**
     * 保存档案数据
     */


    /**
     * 初始化档案
     */
    @PostConstruct
    public void createArchiveFileIndexDoc() {
        log.info("init archive document start ... ");
        // 尝试获取锁
        if (redisCache.tryLock(LOCK, 5, TimeUnit.SECONDS)) {
            try {
                // 创建档案
                log.info("Lock acquired! Executing business logic...");
                // 查询是否创建过档案
                final String baseUrl = getUrl() + "/" + IndexConstants.ARCHIVE_FILE;
                String response = HttpUtil.get(baseUrl);
                log.info("archive file create index response : {}", response);
                if (StrUtil.contains(response, IndexConstants.MAPPINGS) && StrUtil.contains(response, IndexConstants.SETTINGS)) {
                    log.info("archive file index exist ...");
                } else {
                    // 不存在, 创建档案
                    log.info("archive file index not exist ...");
                    String archiveFileJson = JsonFileUtils.readJsonFromClassPath("/index/archive_file.json");
                    if(StrUtil.isNotBlank(archiveFileJson)){
                        log.info("archive file create index");
                        String res = HttpUtils.doRequest(baseUrl, Method.PUT, null, "application/json", null, archiveFileJson);
                        log.info("createArchiveFileIndexDoc archive file create index res：{}", res);
                    }
                }
            } finally {
                // 确保释放锁
                redisCache.unlock(LOCK, "locked");
                log.info("Lock released!");
            }
        } else {
            log.info("Could not acquire lock, try again later.");
        }
    }




    /**
     * 获取档案的请求地址
     */
    private String getUrl() {
        String host = environment.getProperty("elasticsearch.host");
        String port = environment.getProperty("elasticsearch.port");
        return StrUtil.format("http://{}:{}", host, port);
    }

}
